package com.nd.android.musicboxlibrary.ui.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.common.utils.StarAppUtils;
import com.google.gson.Gson;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.Album;
import com.nd.android.musicboxlibrary.business.bean.FileInfo;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.BusProvider;
import com.nd.android.musicboxlibrary.business.comm.MenuPositionEvent;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.adapter.JayMusicSingleAdapter;
import com.nd.android.musicboxlibrary.ui.adapter.JayMusicSpecialAdapter;
import com.nd.android.musicboxlibrary.ui.common.UnMixable;
import com.nd.android.musicboxlibrary.ui.common.ViewInjectorWithReflect;
import com.nd.android.musicboxlibrary.ui.jaymusicbox.search.JayMusicSearchActivity;
import com.nd.android.musicboxlibrary.ui.player.PlayerActivity;
import com.nd.android.musicboxlibrary.ui.view.IndexableListView;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.NdTask;
import com.ngds.library.downloadcenter.AppDownloadHelper;
import com.ngds.library.downloadcenter.AppDownloadHelperImpl;
import com.squareup.otto.Subscribe;

/**
 * <br>
 * Created 2014年7月8日 上午12:00:14
 * 
 * @author wat.ztag
 * @see
 */
@SuppressLint("NewApi")
public class JayMusicFragment extends Fragment implements OnClickListener {

	private int lstSum;

	private ViewHolder holder = new ViewHolder();

	/**
	 * <br>
	 * Created 2014年9月11日 下午11:41:25
	 * 
	 * @author wat.ztag
	 * @version JayMusicFragment
	 * @see
	 */
	private class ViewHolder implements UnMixable {
		IndexableListView lst;
		ListView lstSpecial;
		TextView txtSingle, txtSingleNum;
		TextView txtSpecial, txtSpecialNum;
		FrameLayout pnlSingle;
		FrameLayout pnlSpecial;
		LinearLayout pnlSearch, pnlSearchBar;
		View vSingle, vSpecial;
		TextView txtTitle;
		ImageView btnLeft, btnRight;
		LinearLayout lstErro, lstSpecialErro;
		Button btnLstTry, btnlstSpecialTry;
	}

	@Override
	public void onResume() {
		super.onResume();
		BusProvider.getInstance().register(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		BusProvider.getInstance().unregister(this);
	}

	/**
	 * <br>
	 * Created 2014年9月11日 下午11:41:30
	 * 
	 * @param event MenuPositionEvent
	 * @author wat.ztag
	 */
	@Subscribe
	public void selectionByPosition(MenuPositionEvent event) {
		int sum = ConfigHelper.getInstance(getActivity()).loadIntKey(
				ConfigHelper.CONFIG_KEY_LIST_SUM + "jay", 0);
		if (sum < lstSum) {
			if (holder.lst.getLastVisiblePosition() == event.mPosition) {
				holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
			} else if (holder.lst.getLastVisiblePosition() - 1 == event.mPosition) {
				// holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
				Log.i(event.toString());
			}
		} else {
			if (holder.lst.getLastVisiblePosition() == event.mPosition) {
				// holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
				Log.i(event.toString());
			}
		}
	}

	private JayMusicSingleAdapter mSingleAdapter;

	private JayMusicSpecialAdapter mSpecialAdapter;

	private List<MusicInfo> singles = new ArrayList<MusicInfo>();

	private List<Album> specials = new ArrayList<Album>();

	private DownloadReceiver mDownloadReceiver;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.mbx_jay_music_activity, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		ViewInjectorWithReflect.injectView(holder, this);
		initData();
		setupView();
		addListeners();

		mDownloadReceiver = new DownloadReceiver();
		getActivity().registerReceiver(mDownloadReceiver,
				new IntentFilter(AppDownloadHelper.ACTION_DOWNLOAD_COMPLETE));

		new GetAlbumList(getActivity(), 0).executeByVersion();
		new GetMusicList(getActivity(), R.string.mbx_runing).executeByVersion();
	}

	@Override
	public void onDestroy() {
		if (mDownloadReceiver != null) {
			getActivity().unregisterReceiver(mDownloadReceiver);
		}
		super.onDestroy();
	}

	/**
	 * <br>
	 * Created 2014年9月11日 下午11:41:34
	 * 
	 * @author wat.ztag
	 */
	 protected void initData() {
		 holder.txtTitle.setText(R.string.mbx_jaymusic_title);
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:41:38
	  * 
	  * @author wat.ztag
	  */
	 private void setupView() {

		 holder.btnLeft.setVisibility(View.INVISIBLE);
		 holder.btnRight.setVisibility(View.VISIBLE);
		 mSingleAdapter = new JayMusicSingleAdapter(this.getActivity());
		 mSingleAdapter.setDatas(singles);
		 holder.lst.setAdapter(mSingleAdapter);
		 holder.lst.setFastScrollEnabled(true);

		 mSpecialAdapter = new JayMusicSpecialAdapter(this.getActivity());
		 mSpecialAdapter.setDatas(specials);
		 holder.lstSpecial.setAdapter(mSpecialAdapter);

		 //黄江 2014-12-17  14:41:42
		 //需求是 点击jay的乐盒时默认显示的是单曲分页
		 // modify by jiangwb
		 initTabSingle();
		 //initTabSpecial();
		 StarAppUtils.setViewTypeFace(holder.txtSingle, false);
		 StarAppUtils.setViewTypeFace(holder.txtSingleNum, false);
		 StarAppUtils.setViewTypeFace(holder.txtSpecial, false);
		 StarAppUtils.setViewTypeFace(holder.txtSpecialNum, false);
		 StarAppUtils.setViewTypeFace(holder.txtTitle, false);
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:41:41
	  * 
	  * @author wat.ztag
	  */
	 private void addListeners() {
		 holder.btnLstTry.setOnClickListener(this);
		 holder.btnlstSpecialTry.setOnClickListener(this);
		 holder.pnlSingle.setOnClickListener(this);
		 holder.pnlSpecial.setOnClickListener(this);
		 holder.pnlSearch.setOnClickListener(this);
		 holder.lstSpecial.setOnItemClickListener(mSpecialAdapter);
		 holder.lst.setOnItemClickListener(mSingleAdapter);
		 holder.btnRight.setOnClickListener(this);
		 holder.lst.setOnScrollListener(new OnScrollListener() {

			 @Override
			 public void onScrollStateChanged(AbsListView arg0, int arg1) {
			 }

			 @Override
			 public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				 lstSum = arg2;
				 int sum = ConfigHelper.getInstance(getActivity()).loadIntKey(
						 ConfigHelper.CONFIG_KEY_LIST_SUM + "jay", arg2 + 1);
				 if (arg2 < sum && arg2 != 0) {
					 ConfigHelper.getInstance(getActivity()).saveIntKey(
							 ConfigHelper.CONFIG_KEY_LIST_SUM + "jay", arg2);
				 }
			 }
		 });
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:41:44
	  * 
	  * @author wat.ztag
	  */
	 private void initTabSingle() {
		 holder.txtSingle.setSelected(true);
		 holder.txtSingleNum.setSelected(true);
		 holder.txtSpecial.setSelected(false);
		 holder.txtSpecialNum.setSelected(false);
		 holder.vSingle.setVisibility(View.VISIBLE);
		 holder.vSpecial.setVisibility(View.INVISIBLE);
		 holder.pnlSearchBar.setVisibility(View.VISIBLE);
		 holder.lst.setVisibility(View.VISIBLE);
		 holder.lstSpecial.setVisibility(View.GONE);
		 holder.lstErro.setVisibility(View.GONE);
		 holder.lstSpecialErro.setVisibility(View.GONE);
	 }

	 /**
	  * <br>
	  * Created 2014年11月25日 上午9:18:04
	  * @author       wat.ztag
	  */
	 private void switchTabSingle(){
		 initTabSingle();
		 if(singles.size() <= 0){
			 holder.lstErro.setVisibility(View.VISIBLE);
			 holder.lst.setVisibility(View.GONE);
		 }
	 }

	 /**
	  * <br>
	  * Created 2014年11月25日 上午9:20:07
	  * @author       wat.ztag
	  */
	 private void switchTabSpecial(){
		 initTabSpecial();
		 if(specials.size() <= 0){
			 holder.lstSpecialErro.setVisibility(View.VISIBLE);
			 holder.lstSpecial.setVisibility(View.GONE);
		 }
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:42:04
	  * 
	  * @author wat.ztag
	  */
	 private void initTabSpecial() {
		 holder.txtSingle.setSelected(false);
		 holder.txtSingleNum.setSelected(false);
		 holder.txtSpecial.setSelected(true);
		 holder.txtSpecialNum.setSelected(true);
		 holder.vSingle.setVisibility(View.INVISIBLE);
		 holder.vSpecial.setVisibility(View.VISIBLE);
		 holder.pnlSearchBar.setVisibility(View.GONE);
		 holder.lst.setVisibility(View.GONE);
		 holder.lstSpecial.setVisibility(View.VISIBLE);
		 holder.lstErro.setVisibility(View.GONE);
		 holder.lstSpecialErro.setVisibility(View.GONE);
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:42:16
	  * 
	  * @author wat.ztag
	  */
	 private void sortSingles() {
		 Collections.sort(singles, new Comparator<MusicInfo>() {
			 @Override
			 public int compare(MusicInfo arg0, MusicInfo arg1) {
				 return arg0.getSortKey().compareTo(arg1.getSortKey());
			 }
		 });
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:42:21
	  * 
	  * @author wat.ztag
	  * @version JayMusicFragment
	  * @see
	  */
	 private class GetMusicList extends NdTask {

		 /**
		  * Creates a new instance of GetMusicList. <br>
		  * Created 2014年9月11日 下午11:42:28
		  * 
		  * @param context Context
		  * @param resId int
		  */
		 public GetMusicList(Context context, int resId) {
			 super(context, resId);
		 }

		 @Override
		 protected void doSuccess(Object result) {
			 if (result != null) {
				 singles = (List<MusicInfo>) result;
				 sortSingles();
				 mSingleAdapter.setDatas(singles);
				 holder.txtSingleNum.setText("/" + singles.size());
			 }
		 }

		 @Override
		 protected void doFail(NdException result) {
			 Toast.makeText(mContext, result.getSimpleMsg(), Toast.LENGTH_LONG).show();
		 }

		 @Override
		 protected Object doInBackground(Object... arg0) {
			 try {
				 return ManagerFactory.getPlaylistInstance(getActivity()).getMusicList();
			 } catch (NdException e) {
				 return e;
			 }
		 }
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:42:21
	  * 
	  * @author wat.ztag
	  * @version JayMusicFragment
	  * @see
	  */
	 private class GetMusicWithErroList extends NdTask {

		 /**
		  * Creates a new instance of GetMusicList. <br>
		  * Created 2014年9月11日 下午11:42:28
		  * 
		  * @param context Context
		  * @param resId int
		  */
		 public GetMusicWithErroList(Context context, int resId) {
			 super(context, resId);
		 }

		 @Override
		 protected void doSuccess(Object result) {
			 if (result != null) {
				 singles = (List<MusicInfo>) result;
				 if(singles.size() > 0){
					 sortSingles();
					 mSingleAdapter.setDatas(singles);
					 holder.txtSingleNum.setText("/" + singles.size());
					 holder.lst.setVisibility(View.VISIBLE);
					 holder.lstErro.setVisibility(View.GONE);
				 }else{
					 holder.lst.setVisibility(View.GONE);
					 holder.lstErro.setVisibility(View.VISIBLE);
				 }
			 }else{
				 holder.lst.setVisibility(View.GONE);
				 holder.lstErro.setVisibility(View.VISIBLE);
			 }
		 }

		 @Override
		 protected void doFail(NdException result) {
			 holder.lst.setVisibility(View.GONE);
			 holder.lstErro.setVisibility(View.VISIBLE);
			 Toast.makeText(mContext, result.getSimpleMsg(), Toast.LENGTH_LONG).show();
		 }

		 @Override
		 protected Object doInBackground(Object... arg0) {
			 try {
				 return ManagerFactory.getPlaylistInstance(getActivity()).getMusicList();
			 } catch (NdException e) {
				 return e;
			 }
		 }
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:42:34
	  * 
	  * @author wat.ztag
	  * @version JayMusicFragment
	  * @see
	  */
	 private class GetAlbumList extends NdTask {

		 /**
		  * Creates a new instance of GetAlbumList. <br>
		  * Created 2014年9月11日 下午11:42:38
		  * 
		  * @param context Context
		  * @param resId int
		  */
		 public GetAlbumList(Context context, int resId) {
			 super(context, resId);
		 }

		 @Override
		 protected void doSuccess(Object result) {
			 if (result != null) {
				 specials = (List<Album>) result;
				 if(specials.size() > 0){
					 mSpecialAdapter.setDatas(specials);
					 holder.txtSpecialNum.setText("/" + specials.size());
				 }else{
					 holder.lstSpecial.setVisibility(View.GONE);
					 holder.lstSpecialErro.setVisibility(View.VISIBLE);
				 }
			 }else{
				 holder.lstSpecial.setVisibility(View.GONE);
				 holder.lstSpecialErro.setVisibility(View.VISIBLE);
			 }
		 }

		 @Override
		 protected void doFail(NdException result) {
			 holder.lstSpecial.setVisibility(View.GONE);
			 holder.lstSpecialErro.setVisibility(View.VISIBLE);
			 Toast.makeText(mContext, result.getSimpleMsg(), Toast.LENGTH_LONG).show();
		 }

		 @Override
		 protected Object doInBackground(Object... arg0) {
			 try {
				 return ManagerFactory.getPlaylistInstance(getActivity()).getAlbumList();
			 } catch (NdException e) {
				 return e;
			 }
		 }
	 }

	 /**
	  * <br>
	  * Created 2014年9月11日 下午11:42:45
	  * 
	  * @author wat.ztag
	  * @version JayMusicFragment
	  * @see
	  */
	 private class DownloadReceiver extends BroadcastReceiver {

		 @Override
		 public void onReceive(Context context, Intent intent) {
			 String action = intent.getAction();
			 if (AppDownloadHelper.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

				 try {
					 long downloadId = intent.getLongExtra(AppDownloadHelper.EXTRA_DOWNLOAD_ID, 0);
					 String url = intent.getStringExtra(AppDownloadHelper.EXTRA_DOWNLOAD_URI);
					 AppDownloadHelper appDownloadHelperImpl = AppDownloadHelperImpl
							 .getInstance(getActivity().getApplicationContext());
					 if (!TextUtils.isEmpty(appDownloadHelperImpl.getFileName(downloadId))) {
						 String description = appDownloadHelperImpl.getDescription(context, url);
						 FileInfo fileInfo = new Gson().fromJson(description, FileInfo.class);
						 if (fileInfo != null &&  (fileInfo.getType() == FileInfo.TYPE_MUSIC 
								 || fileInfo.getType() == FileInfo.TYPE_HQ_MUSIC)) {
							 //by jiangwb
							 new GetMusicList(JayMusicFragment.this.getActivity(), 0)
							 .executeByVersion();
						 }
					 }
				 } catch (Exception e) {
					 Log.d("DownloadSuccessReceiver JayMusic");
				 }
			 }
		 }
	 }

	 @Override
	 public void onClick(View v) {
		 int id = v.getId();

		 if (id == R.id.pnlSingle) {
			 switchTabSingle();
			 holder.lst.setAdapter(mSingleAdapter);
			 mSingleAdapter.setDatas(singles);

		 } else if (id == R.id.pnlSpecial) {
			 switchTabSpecial();
			 holder.lst.setAdapter(mSpecialAdapter);
			 mSpecialAdapter.setDatas(specials);

		 } else if (id == R.id.pnlSearch) {
			 PlayerActivity.addSubActivity(this.getActivity());
			 startActivity(new Intent(this.getActivity(), JayMusicSearchActivity.class));

		 } else if (id == R.id.btnRight) {
			 getActivity().finish();

		 } else if(id == R.id.btnLstTry){
			 new GetMusicWithErroList(getActivity(), R.string.mbx_runing).executeByVersion();
		 } else if(id == R.id.btnlstSpecialTry){
			 new GetAlbumList(getActivity(), R.string.mbx_runing).executeByVersion();
		 }
	 }
}
